import ResType from './type/ResType.js'
import {Laf, Tag, Laf_Tag} from '../mongo'
import lafTool from './laf/index.js'
import ptimeApi from '../tool/ptime'
import {oauthPathGen} from '../tool/oauth'
import _ from 'lodash'

const routes = [
	{
		name: '获取lost列表',
		path: '/lost',
		method: 'get',
		view: 'index',
		handler: async function ({limit, ctx}) {
			limit = limit ? limit : 10
			let lafs = await Laf.getLostList(limit)
			lafs = lafTool.dbModelToViewModels(lafs)
			if (ctx.session.token) {
				lafs = lafTool.addAuthInfos(lafs, ctx.state.user.id)
			}
			return new ResType(0, null, {
				list: lafs,
				type: 0,
				token: ctx.session.token
			})
		},
	},
	{
		name: '获取更多lost列表',
		path: '/lost/more',
		method: 'get',
		handler: async function ({id, limit, ctx}) {
			limit = limit ? limit : 5
			let lafs = await Laf.getMoreLostList(id, limit)
			lafs = lafTool.dbModelToViewModels(lafs)
			if (ctx.session.token) {
				lafs = lafTool.addAuthInfos(lafs, ctx.state.user.id)
			}
			return new ResType(0, null, lafs)
		},
	},
	{
		name: '获取found列表',
		path: '/found',
		method: 'get',
		view: 'index',
		handler: async ({limit, ctx}) => {
			limit = limit ? limit : 10
			let lafs = await Laf.getFoundList(limit)
			lafs = lafTool.dbModelToViewModels(lafs)
			if (ctx.session.token) {
				lafs = lafTool.addAuthInfos(lafs, ctx.state.user.id)
			}
			return new ResType(0, null, {
				list: lafs,
				type: 1,
				token: ctx.session.token
			})
		}
	},
	{
		name: '获取更多found列表',
		path: '/found/more',
		method: 'get',
		handler: async function ({id, limit, ctx}) {
			limit = limit ? limit : 5
			let lafs = await Laf.getMoreFoundList(id, limit)
			lafs = lafTool.dbModelToViewModels(lafs)
			if (ctx.session.token) {
				lafs = lafTool.addAuthInfos(lafs, ctx.state.user.id)
			}
			return new ResType(0, null, lafs)
		},
	},
	{
		name: 'laf详情页面',
		path: '/detail/:id',
		method: 'get',
		view: 'detail',
		handler: async function ({id, ctx}) {
			if (!id) return new ResType(400, '参数错误', null)
			let laf = await Laf.getOneLaf(id)
			laf = laf.toObject(laf)
			if (ctx.session.token) {
				laf = lafTool.addAuthInfo(laf, ctx.state.user.id)
			}
			return new ResType(0, null, {
				laf: laf,
				token: ctx.session.token
			})
		}
	},
	{
		name: 'laf信息添加页面',
		path: '/addPage',
		method: 'get',
		view: 'add',
		handler: async function ({ctx, prepublish, selectedTags, type}) {
			if (prepublish) {
				// selectedTags = selectedTags.split(',')
				// let selectedTagObj = {}
				// selectedTags.forEach((tagId) => {
				// 	selectedTagObj[tagId] = true
				// })
				const token = ctx.session.token
				if (!token) return new ResType(300, oauthPathGen(`/laf/addPage?type=${type}`, 'token'), null)
				let user = ctx.state.user
				if (!user) {
					user = ptimeApi.getUserWithToken(token)
				}
				const tags = await Tag.getTagsByFatherName('类型')
				return new ResType(0, null, {
					token: token,
					tags: tags,
					phone: user.phone,
					selectedTags: selectedTags
				})
			} else {
				if (!ctx.session.token) return new ResType(300, oauthPathGen(`/laf/tagPage?prepublish=1`, 'token'), null)
				return new ResType(300, '/laf/tagPage?prepublish=1', null)
			}
		},
	},
	{
		name: '添加一条laf信息',
		path: '/',
		method: 'post',
		handler: async ({ctx}) => {
			const params = ctx.request.body
			if (!params.token || !params.title) return new ResType(400, '缺少参数', null)
			const user = await ptimeApi.getUserWithToken(params.token)
			// console.log(params)
			// console.log(user)
			const laf = {
				userId: user.id,
				userName: user.name.substring(0, 1) + '同学',
				title: params.title,
				intro: params.intro || '',
  			position: params.position || '',
  			contact: params.contact || '',
			  tags: JSON.parse(params.tags) || [],
			  images: JSON.parse(params.images) || [],
			  type: params.type
			}
			const lafResult = await Laf.createLaf(laf)
			const tags = JSON.parse(params.tags)
			if (tags && tags.length) {
				const laftagResult = await Laf_Tag.createByTagIds(lafResult._id, tags)
			}
			return new ResType(0, null, lafResult._id)
		}
	},
	{
		name: '根据标签获取laf列表',
		path: '/tag',
		method: 'post',
		handler: async function ({type, tags, ctx}) {
			tags = JSON.parse(tags) || []
			let lafs = await Laf_Tag.getLafListByTags(type, tags)
			lafs = lafTool.dbModelToViewModels(lafs)
			if (ctx.session.token) {
				lafs = lafTool.addAuthInfos(lafs, ctx.state.user.id)
			}
			return new ResType(0, null, {
				list: lafs,
				type: 0,
				count: lafs.length,
				token: ctx.session.token
			})
		},
	},
	{
		name: '标签搜索页面',
		path: '/tagPage',
		method: 'get',
		view: 'tagSearch',
		handler: async ({ctx, prepublish}) => {
			const tags = await Tag.getTagsByFatherName('类型')
			return new ResType(0, null, {
				list: tags,
				count: 0,
				prepublish: prepublish
			})
		}
	},
	{
    name: '我的',
    path: '/me',
    method: 'get',
    view: 'me',
    handler: async ({type, limit, ctx}) => {
      if (!ctx.session.token) return new ResType(300, oauthPathGen(`/laf/me`, 'token'), null)
      const user = await ptimeApi.getUserWithToken(ctx.session.token)
      limit = limit ? limit : 10
      type = parseInt(type, 10) ? 1 : 0
      let lafs = await Laf.getMyLaf(type, user.id) //type, userId, limit, id)
      lafs = lafs.map((laf) => {
        laf = laf.toObject(laf)
        if (laf.images.length > 0) {
          laf.image = laf.images[0]
        }
        return laf
      })
      return new ResType(0, null, {
        list: lafs,
        type: 0,
        token: ctx.session.token
      })
    }
  },
  {
    name: '我的更多',
    path: '/me/more',
    method: 'get',
    handler: async ({id, type, limit, ctx}) => {
      if(!id) return ResType(400, '缺少参数', null)
      if (!ctx.session.token) return new ResType(400, '您还没有登录', null)
      const user = await ptimeApi.getUserWithToken(ctx.session.token)
      limit = limit ? limit : 10
      type = parseInt(type, 10) ? 1 : 0
      let lafs = await Laf.getMyLaf(type, user.id, limit, id) //type, userId, limit, id)
      lafs = lafs.map((laf) => {
        laf = laf.toObject(laf)
        if (laf.images.length > 0) {
          laf.image = laf.images[0]
        }
        return laf
      })
      return new ResType(0, null, {
        list: lafs
      })
    }
  },
  {
    name: '删除laf',
    path: '/:id',
    method: 'del',
    handler: async ({id, ctx}) => {
    	if(!id) return ResType(400, '非法操作', null)
      if(!ctx.session.token) return ResType(400, '非法操作', null)
      const result = await Laf.deleteLaf(id)
      return new ResType(0, null, '')
		}
  }
];

export default routes;